import * as THREE from 'three';
import { Color } from 'three';
import BaseThreeApp from '../BaseThreeApp';

class _4_01Light extends BaseThreeApp {
  public scene: THREE.Scene;
  public camera: THREE.PerspectiveCamera;
  public renderer: THREE.WebGLRenderer;

  start() {
    this.scene = new THREE.Scene();
    this.camera = new THREE.PerspectiveCamera(
      60,
      this.clientWidth / this.clientHeight,
      0.1,
      1000
    );
    this.camera.position.z = 9;

    this.renderer = new THREE.WebGLRenderer({
      canvas: this.element,
      antialias: true,
    });

    this.renderer.setDrawingBufferSize(this.clientWidth, this.clientHeight, 1);

    const geometry = new THREE.BoxGeometry(1, 1, 1);
    const material = new THREE.MeshLambertMaterial({ color: 0x00ffff });
    const cube = new THREE.Mesh(geometry, material);
    this.scene.add(cube);

    const material2 = new THREE.MeshLambertMaterial({ color: 0xffffff });
    const cube2 = new THREE.Mesh(geometry, material2);
    cube2.position.x = 2;
    cube2.rotation.x = 0.3;
    cube2.rotation.y = 0.6;
    this.scene.add(cube2);

    const geometry2 = new THREE.CylinderGeometry(0.5, 0.8, 1, 90);
    const cylinder = new THREE.Mesh(geometry2, material2);
    cylinder.position.x = -2;
    cylinder.rotation.x = 0.3;
    this.scene.add(cylinder);

    const ambient = new THREE.AmbientLight(0xff00ff, 0.2);
    this.scene.add(ambient);

    const pointLight = new THREE.PointLight(0xffffff, 0.3);
    pointLight.position.set(-5, 5, 0);
    this.scene.add(pointLight);

    const dirLight = new THREE.DirectionalLight(0xffff00, 1);
    dirLight.position.set(0, 0, 5);
    dirLight.target.position.set(0, 0, 0);
    this.scene.add(dirLight);
    this.isRunning = true;
    const animate = (time) => {
      if (!this.isRunning || this.element === null) {
        return;
      }
      this.renderer.render(this.scene, this.camera);
      requestAnimationFrame(animate);
      cube.rotation.x = 0.001 * time;
      cube.rotation.y = 0.001 * time;
    };
    animate(0);
  }

  onresize(e: UIEvent) {
    super.onresize(e);
    console.log('onresive');
    if (this.renderer) {
      this.renderer.setDrawingBufferSize(
        this.clientWidth,
        this.clientHeight,
        1
      );
      if (this.camera) {
        this.camera.aspect = this.clientWidth / this.clientHeight;
        this.camera.updateProjectionMatrix();
      }
    }
  }
}

export default new _4_01Light();
